<template>
  <div class="academic-form">
    <el-form :model="form" label-width="100px" size="small">
      <el-form-item label="课程名称" required>
        <el-input
          v-model="form.courseName"
          placeholder="请输入课程名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="课程成绩" required>
        <el-input-number
          v-model="form.score"
          :min="0"
          :max="100"
          label="课程成绩"
          controls-position="right"
          placeholder="请输入成绩"
        />
      </el-form-item>

      <el-form-item label="是否学位课">
        <el-switch
          v-model="form.isDegreeCourse"
          active-text="是"
          inactive-text="否"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSave">保存成绩</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'AcademicForm',
  data() {
    return {
      form: {
        courseName: '',
        score: null,
        isDegreeCourse: true
      }
    }
  },
  methods: {
    async handleSave() {
      if (!this.form.courseName || this.form.score === null) {
        ElMessage.error('请完整填写所有必填字段')
        return
      }

      const studentId = localStorage.getItem('studentId')

      if (!studentId) {
        ElMessage.error('未检测到登录学号，请重新登录')
        return
      }

      const payload = {
        studentId: Number(studentId),
        courseName: this.form.courseName,
        score: this.form.score,
        isDegreeCourse: this.form.isDegreeCourse
      }

      try {
        const res = await axios.post('/api/academicscores', payload, {
          headers: { 'Content-Type': 'application/json' },
          withCredentials: true
        })

        if (res.data && (res.data.code === 200 || res.data > 0)) {
          ElMessage.success('学业成绩保存成功')
          this.resetForm()
        } else {
          ElMessage.error(res.data.message || '保存失败，请稍后重试')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    },

    resetForm() {
      this.form.courseName = ''
      this.form.score = null
      this.form.isDegreeCourse = true
    }
  }
}
</script>

<style scoped>
.academic-form {
  max-width: 500px;
  background-color: #fafafa;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
</style>
